package fr.generali.accueilclient.gwt.client.ui.components.form.formitem;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.RadioButton;


public class RadioButtonFormItem extends LabelFormItem<String> implements LeafValueEditor<String> {

    private static final int MARGIN_RADIO = 20;

    private List<RadioButton> radioButtons = new ArrayList<RadioButton>();

    protected Map<String, String> valueMap;

    private FlowPanel mainPanel;

    public RadioButtonFormItem(int choices, String groupName) {
        super(new FlowPanel());
        mainPanel = (FlowPanel ) editableWidget;
        mainPanel.removeStyleName(res.style().input());
        generateRadioButtonPanel(choices, groupName);
    }

    private void generateRadioButtonPanel(int choices, String groupName) {
        RadioButton radioButton;
        for (int i = 0; i < choices; i++) {
            radioButton = new RadioButton(groupName);
            radioButtons.add(radioButton);
            radioButton.getElement().getStyle().setMarginRight(MARGIN_RADIO, Unit.PX);
            mainPanel.add(radioButton);
        }
        radioButtons.get(0).setValue(true);
    }

    public void initRadioValues(Map<String, String> values) {
        valueMap = values;
        int i = 0;
        for (String key : values.keySet()) {
            radioButtons.get(i).setFormValue(key);
            radioButtons.get(i++).setText(values.get(key));
        }
    }

    @Override
    protected boolean isDataFilled() {
        boolean isFilled = false;
        for (RadioButton radio : radioButtons) {
            isFilled = isFilled || radio.getValue();
        }
        return isFilled;
    }

    @Override
    protected void doSetValue(String value, boolean valueIsNullOrEmpty) {
        valueLabel.setText(value);
    }

    public void setRadioValue(String value, String text) {
        for (RadioButton radio : radioButtons) {
            if (radio.getText().equals(text)) {
                radio.setValue(true);
                radio.setFormValue(value);
                break;
            }
        }
    }

    @Override
    protected boolean valueIsNullOrEmpty(String value) {
        return value == null;
    }

    public void addValueChangeHandler(ValueChangeHandler<Boolean> handler) {
        for (RadioButton radio : radioButtons) {
            radio.addValueChangeHandler(handler);
        }
    }

    @Override
    public String getValue() {
        for (RadioButton radio : radioButtons) {
            if (radio.getValue()) {
                return radio.getFormValue();
            }
        }
        return null;
    }

}
